import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Button, message, Spin } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import ApiOverviewCards from './ApiOverviewCards';
import ApiTypeDistributionChart from './ApiTypeDistributionChart';
import ApiRiskAnalysisChart from './ApiRiskAnalysisChart';
import ApiClassificationChart from './ApiClassificationChart';
import {
    getApiStatisticsOverview,
    getApiTypeDistribution,
    getApiRiskAnalysis,
    getApiClassificationStats,
    type ApiStatisticsOverview,
    type ApiTypeDistribution,
    type ApiRiskAnalysis,
    type ApiClassificationStats
} from '../../../services/apiStatistics';

interface ApiSummaryAnalysisProps {
    unitId: string;
}

const ApiSummaryAnalysis: React.FC<ApiSummaryAnalysisProps> = ({ unitId }) => {
    // 状态管理
    const [loading, setLoading] = useState(false);
    const [overviewData, setOverviewData] = useState<ApiStatisticsOverview | null>(null);
    const [typeDistributionData, setTypeDistributionData] = useState<ApiTypeDistribution[]>([]);
    const [riskAnalysisData, setRiskAnalysisData] = useState<ApiRiskAnalysis | null>(null);
    const [classificationData, setClassificationData] = useState<ApiClassificationStats | null>(null);

    // 加载所有统计数据
    const loadAllStatistics = async () => {
        if (!unitId) {
            message.warning('单元ID不能为空');
            return;
        }

        setLoading(true);
        try {
            // 并行加载所有统计数据
            const [overview, typeDistribution, riskAnalysis, classification] = await Promise.all([
                getApiStatisticsOverview(unitId),
                getApiTypeDistribution(unitId),
                getApiRiskAnalysis(unitId),
                getApiClassificationStats(unitId)
            ]);

            setOverviewData(overview);
            setTypeDistributionData(Array.isArray(typeDistribution) ? typeDistribution : []);
            setRiskAnalysisData(riskAnalysis);
            setClassificationData(classification);

            message.success('API汇总数据加载完成');
        } catch (error) {
            console.error('加载API统计数据失败:', error);
            message.error('加载API汇总数据失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 页面初始化时加载数据
    useEffect(() => {
        if (unitId) {
            loadAllStatistics();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [unitId]);

    // 手动刷新数据
    const handleRefresh = () => {
        loadAllStatistics();
    };

    return (
        <div style={{ padding: '0 24px' }}>
            {/* 页面标题和操作按钮 */}
            <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                marginBottom: '24px',
                padding: '16px 24px',
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                borderRadius: '12px',
                boxShadow: '0 4px 20px rgba(102, 126, 234, 0.3)'
            }}>
                <div>
                    <h2 style={{ 
                        color: '#fff', 
                        margin: 0, 
                        fontSize: '24px',
                        fontWeight: 'bold'
                    }}>
                        📊 汇总分析
                    </h2>
                    <p style={{ 
                        color: 'rgba(255,255,255,0.8)', 
                        margin: '8px 0 0 0',
                        fontSize: '14px'
                    }}>
                        全面分析API接口的类型分布、风险状况和分类统计
                    </p>
                </div>
                <Button
                    type="primary"
                    icon={<ReloadOutlined />}
                    onClick={handleRefresh}
                    loading={loading}
                    style={{
                        background: 'rgba(255,255,255,0.2)',
                        border: 'none',
                        color: '#fff',
                        borderRadius: '8px'
                    }}
                >
                    刷新数据
                </Button>
            </div>

            <Spin spinning={loading} tip="正在加载API汇总数据..." size="large">
                <div>
                    {/* API概览卡片 */}
                    <ApiOverviewCards data={overviewData} loading={loading} />

                    {/* 图表区域 */}
                    <Row gutter={[16, 16]}>
                        {/* 第一行：API类型分布 + API风险分析 */}
                        <Col xs={24} lg={12}>
                            <ApiTypeDistributionChart 
                                data={typeDistributionData} 
                                loading={loading} 
                            />
                        </Col>
                        <Col xs={24} lg={12}>
                            <ApiRiskAnalysisChart 
                                data={riskAnalysisData} 
                                loading={loading} 
                            />
                        </Col>
                    </Row>

                    <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
                        {/* 第二行：API分类统计 + 预留扩展位置 */}
                        <Col xs={24} lg={12}>
                            <ApiClassificationChart 
                                data={classificationData} 
                                loading={loading} 
                            />
                        </Col>
                        <Col xs={24} lg={12}>
                            {/* 预留位置：可以添加更多图表 */}
                            <Card 
                                size="small"
                                style={{ 
                                    height: '400px',
                                    borderRadius: '12px',
                                    boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center'
                                }}
                            >
                                <div style={{ 
                                    textAlign: 'center', 
                                    color: '#8c8c8c',
                                    fontSize: '16px'
                                }}>
                                    <div style={{ fontSize: '48px', marginBottom: '16px' }}>📈</div>
                                    <div>更多图表敬请期待</div>
                                    <div style={{ fontSize: '14px', marginTop: '8px' }}>
                                        可根据需要添加API活跃度趋势、调用量分布等图表
                                    </div>
                                </div>
                            </Card>
                        </Col>
                    </Row>

                    {/* 数据概要信息 */}
                    <Card 
                        size="small"
                        style={{ 
                            marginTop: '16px',
                            borderRadius: '12px',
                            background: 'linear-gradient(135deg, #f6f9fc 0%, #ffffff 100%)',
                            border: '1px solid #e8e8e8'
                        }}
                    >
                        <div style={{ textAlign: 'center', color: '#666' }}>
                            <h3 style={{ color: '#333', marginBottom: '16px' }}>
                                💡 统计说明
                            </h3>
                            <Row gutter={[24, 16]}>
                                <Col xs={24} sm={8}>
                                    <div style={{ fontSize: '14px' }}>
                                        <strong>API数据范围：</strong>仅统计 is_entry=true 的接口方法
                                    </div>
                                </Col>
                                <Col xs={24} sm={8}>
                                    <div style={{ fontSize: '14px' }}>
                                        <strong>活跃定义：</strong>具有APM或SA调用记录的API
                                    </div>
                                </Col>
                                <Col xs={24} sm={8}>
                                    <div style={{ fontSize: '14px' }}>
                                        <strong>高风险：</strong>废弃等级为HIGH_RISK或EXTREME_RISK的API
                                    </div>
                                </Col>
                            </Row>
                        </div>
                    </Card>
                </div>
            </Spin>
        </div>
    );
};

export default ApiSummaryAnalysis;